import json
import logging
import re
from django.http import JsonResponse
from django.views import View
from lapi_app.models.testcase_model.testcase import Testcase
from lapi_app.models.testcase_model.testcase_tree import Menu
from lapi_app.models.ui_model.ui_case import UI_case

logger = logging.getLogger('django')


class Testcase_action(View):

    def delete(self, request, *args, **kwargs):
        body = json.loads(request.body)
        ids = body["menu_id"]
        cases = Menu.objects.filter(id=ids)
        if cases.exists():
            for case in cases:
                if case.type == 2:
                    testcase = Testcase.objects.filter(id=case.testcase_id)
                    testcase.delete()
                    case.delete()
                elif case.type == 4:
                    UI_case.objects.filter(id=case.ui_id).delete()
                    case.delete()
            return JsonResponse({
                "code": 200,
                "message": "删除接口成功"
            })
        else:
            return JsonResponse({
                "code": 100,
                "message": "删除接口失败，无此接口"
            })

    def post(self, request, *args, **kwargs):
        global method
        try:
            data = json.loads(request.body)
            id = data["id"]
            type = data["type"]
            detail = data["detail"]
            detail_copy = detail.replace("\n", "").replace(" ", "")
            if "请求示例```json" in detail_copy and type == 1:
                key = re.compile(u'请求示例```json.*')
                a = key.findall(detail_copy)
                b = a[0].replace("```", "").replace("请求示例json[", "[")
                c = b.split("','")
                menu_list = []
                for i in eval(c[0]):
                    if i["method"] == "GET" or i["method"] == "get":
                        method = 1
                    elif i["method"] == "POST" or i["method"] == "post":
                        method = 2
                    elif i["method"] == "PUT" or i["method"] == "put":
                        method = 3
                    elif i["method"] == "DELETE" or i["method"] == "delete":
                        method = 4
                    case = Testcase.objects.create(
                        t_name=i["name"], t_method=method, t_url=i["url"], t_header=i["header"],
                        t_body=i["body"], t_user_id=data["user_id"], t_case_detail=detail
                    )
                    menu = Menu.objects.create(label=i["name"], pid=id, testcase_id=case.id, type=2,
                                               m_user_id=data["user_id"])
                    menu_list.append({"id": menu.id, "type": 2, "label": i["name"], "pid": id})
                return JsonResponse({
                        "code": 200,
                        "message": "上传接口说明文件成功",
                        "detail": detail,
                        "data": menu_list
                    })
            elif type == 2:
                Testcase.objects.filter(id=id).update(t_case_detail=detail)
                return JsonResponse({
                    "code": 200,
                    "message": "更新markdown信息成功",
                    "detail": detail
                })
        except Exception as e:
            return JsonResponse({
                "code": 100,
                "message": str(e)
            })
